package com.googlecode.cswish.struts.hibernate.ehcache;

import java.util.Map;

import net.sf.ehcache.Element;
import net.sf.ehcache.search.attribute.AttributeExtractor;
import net.sf.ehcache.search.attribute.AttributeType;
import net.sf.ehcache.search.expression.BaseCriteria;

public class IgnoreTypeEqualTo extends BaseCriteria {

    private final Object value;
    private final String attributeName;
    private final AttributeType type;

    /**
     * Constructor
     *
     * @param attributeName attribute name
     * @param value
     */
    public IgnoreTypeEqualTo(String attributeName, Object value) {
        if (value == null || attributeName == null) {
            throw new NullPointerException();
        }

        this.attributeName = attributeName;
        this.value = value;

        this.type = AttributeType.typeFor(attributeName, value);
    }

    /**
     * Get attribute value.
     *
     * @return attribute value
     */
    public Object getValue() {
        return value;
    }

    /**
     * Get attribute name.
     *
     * @return attribute name.
     */
    public String getAttributeName() {
        return attributeName;
    }

    /**
     * Get attribute type.
     *
     * @return attribute type.
     */
    public AttributeType getType() {
        return type;
    }

    /**
     * {@inheritDoc}
     */
    public boolean execute(Element e, Map<String, AttributeExtractor> attributeExtractors) {
        Object attributeValue = attributeExtractors.get(attributeName).attributeFor(e, getAttributeName());
        if (attributeValue == null) {
            return false;
        } else {
        	AttributeType attrType = AttributeType.typeFor(getAttributeName(), attributeValue);
            if (!getType().equals(attrType)) {
                return attributeValue.toString().equals(value.toString());
            } else {
            	return attributeValue.equals(value);
            }
        }
    }
}
